package com.hj.web.filter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.hj.biz.dao.SysRegisterSystemDao;
import com.hj.biz.dao.entity.SysRegisterSystem;
import com.hj.constants.CommonConstants;
import com.hj.model.ReturnResponse;

/**
 * @author dehui dou
 * @date 2020/10/3 19:47
 * @description 权限认证filter
 */
public class AuthFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(AuthFilter.class);

    private SysRegisterSystemDao sysRegisterSystemDao;

    @Override
    public void init(FilterConfig filterConfig) {
        ServletContext servletContext = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        sysRegisterSystemDao = ctx.getBean("sysRegisterSystemDao", SysRegisterSystemDao.class);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        String authorization = req.getParameter(CommonConstants.AUTHORIZATION);
        if (StringUtils.isEmpty(authorization)) {
            String systemCode = req.getHeader(CommonConstants.SYSTEM_CODE);
            String privateKey = req.getHeader(CommonConstants.PRIVATE_KEY);
            if (StringUtils.isEmpty(systemCode) || StringUtils.isEmpty(privateKey)) {
                doError(res);
                return;
            }
            SysRegisterSystem sysRegisterSystem =
                sysRegisterSystemDao.getOneByCodeAndPrivateKey(systemCode, privateKey);
            if (sysRegisterSystem == null) {
                doError(res);
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private static void doError(HttpServletResponse response) {
        ReturnResponse<Object> result = new ReturnResponse<>(401, "认证失败！", null);
        PrintWriter writer = null;
        OutputStreamWriter osw = null;
        try {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
            writer = new PrintWriter(osw, true);
            String jsonStr = JSON.toJSONString(result);
            writer.write(jsonStr);
            writer.flush();
        } catch (Exception e) {
            logger.error("过滤器返回信息失败:" + e.getMessage(), e);
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != osw) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
